import funccollect.config as fc

from pathlib import Path

from fastapi import APIRouter, HTTPException, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse

from funccollect.comic_generator import Comic_Gen

api_router = APIRouter()
cg = Comic_Gen()
templates = Jinja2Templates(directory=str(Path(__file__).parent.parent / Path('templates')))


@api_router.get('/neko/{chapter}/{word}', tags=["漫画获取"])
async def get_pic(chapter: str,
                  word: str):
    """
    获取漫画对应页数

    - **chapter**: 章节数
    - **word**: 话数
    """
    pic_list = cg.get_pic_url(chapter, word)
    return {'comic-list': [f'{chapter}/{word}/{num.name}' for num in pic_list]}


@api_router.get('/neko-chapters', tags=["漫画页码获取"])
async def get_chapters():
    """
    获取漫画章数
    """
    return {'chapters': cg.get_chapter_list()}


@api_router.get('/neko-words/{chapter}', tags=["漫画页码获取"])
async def get_words(chapter: str):
    """
    获取对应章数下的话数

    - **chapter**: 所选章数
    """
    if words := cg.get_word_list(chapter):
        return {'words': words}
    raise HTTPException(status_code=404, detail="输入范围错误")


@api_router.get('/index', response_class=HTMLResponse)
async def index(request: Request):
    if '127.0.0.1' in request.headers.get('host'):
        ip_port = request.headers.get('host')
    else:
        ip_port = fc.get_ip_port()
    return templates.TemplateResponse('index.html',
                                      {"request": request,
                                       "title": "海猫鸣泣之时",
                                       "ip_port": ip_port})
